/*
 * Copyright (C) 2013 tangzhi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.tangzsoft.pdmviewer.storage.memory;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.tangzsoft.pdmviewer.model.PdmObjectRel.RelType;
import org.tangzsoft.pdmviewer.storage.spi.PdmObjectRelDAOSPI;
import org.tangzsoft.pdmviewer.storage.spi.StorageSPI;


public class PdmObjectRelDAOSPIImpl implements PdmObjectRelDAOSPI {

    protected StorageSPI storage;
    
    
    /**
     * 对象关系表
     * 层次关系： fileId - RelType - parentId - childId
     */
    private Map<String, Map<RelType, Map<String, List<String>> > > fileObjectRel;
    
    PdmObjectRelDAOSPIImpl(MemoryStorageSPIImpl storage) {
        this.storage = storage;
        
        fileObjectRel = new HashMap<String, Map<RelType, Map<String, List<String>> > >();
    }

    @Override
    public void create(RelType relType, String fileId, String parentId, String childId) {
        
        Map<RelType, Map<String, List<String>>> objRel;
        if (fileObjectRel.containsKey(fileId)) {
            objRel = fileObjectRel.get(fileId);
        }else{
            objRel = new EnumMap<RelType, Map<String, List<String>>>(RelType.class);
            fileObjectRel.put(fileId, objRel);
        }
        
        Map<String, List<String>> parentChild;
        if (objRel.containsKey(relType)) {
            parentChild = objRel.get(relType);
        }else{
            parentChild = new HashMap<String, List<String>>();
            objRel.put(relType, parentChild);
        }
        
        List<String> children;
        if (parentChild.containsKey(parentId)) {
            children = parentChild.get(parentId);
        }else{
            children = new ArrayList<String>();
            parentChild.put(parentId, children);
        }
        
        children.add(childId);
    }

    @Override
    public String[] findChildren(String fileId, RelType relType, String parentId) {
        List<String> children = fileObjectRel.get(fileId).get(relType).get(parentId);
        return children.toArray(new String[children.size()]);
    }
    
}
